const express = require('express');
const router = express.Router();
const Category = require('../../models/category');
const { generateId } = require('../../utils/auth');

// 获取分类列表
router.get('/list', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, name, status } = req.query;
    const query = {};

    if (name) {
      query.name = new RegExp(name, 'i');
    }
    if (status !== undefined) {
      query.status = status === 'true';
    }

    const total = await Category.countDocuments(query);
    const categories = await Category.find(query)
      .skip((page - 1) * pageSize)
      .limit(Number(pageSize))
      .sort({ sort: 1, createdAt: -1 });

    res.json({
      success: true,
      data: {
        list: categories,
        total,
        page: Number(page),
        pageSize: Number(pageSize)
      }
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 创建分类
router.post('/create', async (req, res) => {
  try {
    const categoryData = {
      ...req.body,
      id: generateId('cat_')
    };

    const category = new Category(categoryData);
    await category.save();

    res.json({
      success: true,
      data: category
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 更新分类
router.post('/update', async (req, res) => {
  try {
    const { id, ...updateData } = req.body;

    const category = await Category.findOneAndUpdate(
      { id },
      updateData,
      { new: true }
    );

    if (!category) {
      return res.status(404).json({
        code:500,
        message: '分类不存在'
      });
    }

    res.json({
      success: true,
      data: category
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 删除分类
router.post('/delete', async (req, res) => {
  try {
    const { id } = req.body;

    // 检查是否有关联的产品
    const hasProducts = await Product.exists({ category: id });
    if (hasProducts) {
      return res.status(400).json({
        code:500,
        message: '该分类下存在产品，无法删除'
      });
    }

    const category = await Category.findOneAndDelete({ id });
    if (!category) {
      return res.status(404).json({
        code:500,
        message: '分类不存在'
      });
    }

    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

// 获取分类详情
router.get('/:id', async (req, res) => {
  try {
    const category = await Category.findOne({ id: req.params.id });

    if (!category) {
      return res.status(404).json({
        code:500,
        message: '分类不存在'
      });
    }

    res.json({
      success: true,
      data: category
    });
  } catch (error) {
    res.status(500).json({
      code:500,
      message: error.message
    });
  }
});

module.exports = router; 